package com.by.zhdoctor.huanxin.util;


import com.google.gson.Gson;
import io.swagger.client.ApiException;
import io.swagger.client.api.AuthenticationApi;
import io.swagger.client.model.Token;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * 获取环信token的工具类
 * Created by succy on 17-9-3.
 */
public final class TokenUtil {
    private static final Logger log = LoggerFactory.getLogger(TokenUtil.class);
    private static Token tokenBody;
    private static AuthenticationApi authApi = new AuthenticationApi();
    private static String accessToken;
    private static Double expiredate = -1D;

    static {
        tokenBody = new Token().clientId(HuanXinInfo.CLIENT_ID)
            .grantType(HuanXinInfo.GRANT_TYPE)
            .clientSecret(HuanXinInfo.CLIENT_SECRET);
    }

    private TokenUtil() {

    }

    /**
     * 初始化token
     */
    public static void initToken() {
        String respStr = null;
        try {
            respStr = authApi.orgNameAppNameTokenPost(HuanXinInfo.ORG_NAME, HuanXinInfo.APP_NAME, tokenBody);
        }catch (ApiException e) {
            log.error("[异常] 初始化token发生错误, msg:{}", e.getMessage());
        }

        Gson gson = new Gson();
        Map json = gson.fromJson(respStr, Map.class);
        accessToken = " Bearer " + json.get("access_token");
        expiredate = System.currentTimeMillis() + (Double)json.get("expires_in");
    }

    private static Boolean isExpired() {
        return System.currentTimeMillis() > expiredate;
    }

    /**
     * 获取token
     * @return 获取到的token
     */
    public static String getAccessToken() {
        if (accessToken == null || isExpired()) {
            initToken();
        }
        return accessToken;
    }
}
